const request = require('request')
var NodeCache = require('node-cache') ;
var wxconfig = require('./wxconfig');
var myCache = new NodeCache({  stdTTL :3600 ,  checkperiod :3600 });
const access_token = require('./getaccesstoken')

var getJsticket = function () {
    return new Promise(function (resolve,reject) {
        var token = myCache.get( "ACCESS_TOKEN" );
        if(token){
            resolve(token)
        }else{
            access_token().then((access_token) => {
                request.get({
                    uri: wxconfig.jsTicketLink,
                    json: true,
                    qs: {
                        access_token: access_token,
                        type: 'jsapi'
                    }
                }, (err, res, body) => {
                    if (err) {
                        reject(err)
                    }
                    if (body.errcode) {
                        reject(body.errcode)
                    }

                    myCache.set('JSTICKET',body.ticket,function(err,success){
                        if( !err && success ){
                            var  tempvalue = myCache.get( "JSTICKET" );
                            resolve(tempvalue)
                        }
                    })
                })
            })
        }

    })
}

module.exports = getJsticket
